import app from '@/utils/app.js'
import Config from '@/config/index.js'
import {
	fetchCode2Session,
} from '@/services/user.js'
import Vue from 'vue'
import Vuex from 'vuex'
import {
	getAccountBalanceInfo,
	getUserinfo,
	weChatLogin,
} from '@/services/promotion.js'
Vue.use(Vuex)


const user = {
	state: {
		token: uni.getStorageSync('token'),
		openId: '', // 小程序用户唯一值
		session3rd: '',
		isLogin: uni.getStorageSync('isLogin'),
		loginInfo: uni.getStorageSync('loginInfo') || {}, // 用户信息,
		userInfo: {},
		accountBalance: {}, // 账户信息
		getCodeRequest: null
	},
	getters: {
		userInfo(state) {
			return state.userInfo || {}
		},
		isPush(state) {
			return Boolean(state.loginInfo.promotionGroundPush)
		},
	},
	mutations: {
		// 保存用户sesion和openId
		setUserSessionInfo(state, {
			token,
			avatarUrl,
			nickname
		}) {
			state.token = token
			uni.setStorageSync('token', token)
		},
		// 设置登录信息
		setLoginInfo(state, loginInfo) {
			state.loginInfo = loginInfo
			uni.setStorageSync('loginInfo', loginInfo)
		},
		// 设置登录状态
		setLoginState(state, status) {
			state.isLogin = status
			uni.setStorageSync('isLogin', status)
		},
		// 设置用户信息
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
			uni.setStorageSync('userInfo', userInfo)
		},
		// 设置账号金额
		setAccountBalance(state, data) {
			state.accountBalance = data
		},
		// 清除登录态
		logout(state) {
			state.loginInfo = {}
			state.userInfo = {}
			uni.clearStorageSync()
			uni.redirectTo({
				url: '/pages/login/index',
			})
		},

	},
	actions: {
		// 获取openId和sessiojn
		async getMinaSession({
			commit,
			state
		}) {
			if (state.getCodeRequest) return await state.getCodeRequest
			state.getCodeRequest = new Promise(async (resolve, reject) => {
				try {
					const [err, loginResp] = await uni.login()
					if (err) throw err
					const resp = await fetchCode2Session({
						code: loginResp.code,
					})
					commit('setUserSessionInfo', resp)
					state.getCodeRequest = null
					resolve(resp)
				} catch (e) {
					reject(e)
				}
			})
			return await state.getCodeRequest
		},
		async getUserInfo({
			commit,
		}) {
			const resp = await getUserinfo()
			commit('setUserInfo', resp)
			return resp
		},

		async getAccountBalanceInfo({
			commit,
		}) {
			const data = await getAccountBalanceInfo()
			commit('setAccountBalance', {
				...data,
				balance: data.balance / 100,
				expectedTotalIncomeBalance: data.expectedTotalIncomeBalance / 100,
				withdrawBalance: data.withdrawBalance / 100,
				freezeBalance: data.freezeBalance / 100,
			})
		},
	},
}


export default user
